//////////////////////////////////////////////////////////////////////
//
// MPIComm.cpp: implementation of the CMPIComm class.
//
//////////////////////////////////////////////////////////////////////

#include "stdafx.h"
#include "MPIComm.h"

#include "w95_s7.h"
#include "komfort.h"

#pragma comment(lib,"w95_s7.lib")  
#pragma comment(lib,"komfort.lib") 

#ifdef _DEBUG
#undef THIS_FILE
static char THIS_FILE[]=__FILE__;
#define new DEBUG_NEW
#endif

//////////////////////////////////////////////////////////////////////
// Construction/Destruction
CMPIComm::CMPIComm()
{

}
//
CMPIComm::~CMPIComm()
{

}
/////////////////////////////////////////////////////////////////////////////
bool CMPIComm::InitMPIchannel()
{
	adr_table_type adr_table[2] = { {2,0,2,0},{0,0,0,0}};

	int	res;
       
	error_message(0,"error.dat");
	res = load_tool(1,NULL,adr_table);
	if (res != 0)
	{
	    //MessageBox("Error Init PLC PORT,Add=2 ");
		return false;
	}
    return true;
}
/////////////////////////////////////////////////////////////////////////////
void CMPIComm::CloseMPIComm()
{
	int res =unload_tool(); 

	if (res != 0) 
	{
		//MessageBox("Cannot Close PORT  ADdd=2");
	}
}
//
short int CMPIComm::GetPLCIntEx(unsigned char *x)
{
	static union
	{
		char  iChar[2];
		short int iData;
	}Byte2Int;
	Byte2Int.iChar[0]=*(x+1);
	Byte2Int.iChar[1]=*(x+0);
	return Byte2Int.iData;
}
//

//
bool CMPIComm::ReadPLCDB(int DBNO,int DBStart,int Amount)
{
	if((DBNO>0) && (Amount>0))
	{
		m_iRDWTStateCode=d_field_read(DBNO,DBStart,Amount,m_cRDBUFFER);
		m_iStateCode=0;
		return true;
	}
	else
	{
		m_iStateCode=1000;
		return false;
	}
}
//
int CMPIComm::SetPLCIntEx(short int iValue,unsigned char *x)
{
	static union
	{
		  char  iChar[2];
		  short int iData;
	}Byte2Int;
	Byte2Int.iData=iValue;
	*(x+1)=Byte2Int.iChar[0];
	*(x+0)=Byte2Int.iChar[1];
	return 0;
}
//
bool CMPIComm::WritePLCDB(int DBNO,int DBStart,int Amount)
{
	if((DBNO>0) && (Amount>0))
	{
		m_iRDWTStateCode=d_field_write(DBNO,DBStart,Amount,m_cWTBUFFER);
		m_iStateCode=0;
		return true;
	}
	else
	{
		m_iStateCode=2000;
		return false;
	}
}
